#include "stdafx.h"
#include "SharedReaderUniqueWriter.h"


using namespace syncLib;

SharedReaderUniqueWriter::SharedReaderUniqueWriter( void ) 
    : readersCount_(0), writingAllowedEvent_(NULL), isInitialized_(false)
{
    Initialize();
}

void SharedReaderUniqueWriter::Initialize()
{
    writingAllowedEvent_.Attach(CreateEvent(NULL, TRUE, TRUE, NULL));


    isInitialized_ = (NULL != writingAllowedEvent_);

    if(!isInitialized_)
    {
        throw std::runtime_error("SharedReaderUniqueWriter. Initialization fails");
    }
}

SharedReaderUniqueWriter::~SharedReaderUniqueWriter( void )
{

}

void SharedReaderUniqueWriter::LockReader()
{

    readerSection_.Lock();
    writerSection_.Lock();

    if (++readersCount_ == 1) 
    {
        ResetEvent(writingAllowedEvent_);
    }

    readerSection_.UnLock();
    writerSection_.UnLock();

}

void SharedReaderUniqueWriter::UnlockReader()
{
    readerSection_.Lock();

    assert(readersCount_ > 0);

    if(readersCount_ > 0)
    {
        std::runtime_error("SharedReaderUniqueWriter. readersCount_ >  0 ");
    }

    if (--readersCount_ == 0) 
    {
        SetEvent(writingAllowedEvent_);
    }

    readerSection_.UnLock();
}

void SharedReaderUniqueWriter::LockWriter()
{
    writerSection_.Lock();

    if (readersCount_ > 0)
    {
        WaitForSingleObject(writingAllowedEvent_, INFINITE);
    }
}

void SharedReaderUniqueWriter::UnlockWriter()
{
    writerSection_.UnLock();
}

